package com.example.Repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Repository.FileRepository;
import com.example.dao.TrendsFileDao;
import com.example.pojo.File;
import com.example.pojo.Result;
import com.example.pojo.TrendsFile;
import com.example.service.FileService;
import com.example.utils.AliOssUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @author crt
 */
@Service
public class FileRepositoryImpl implements FileRepository {

    @Resource
    private FileService fileService;
    @Resource
    private TrendsFileDao trendsFileDao;

    @Override
    public Result<List<Integer>> upload(MultipartFile[] fileList) throws Exception {
        List<Integer> fileIdList = new ArrayList<>();
        for (MultipartFile file : fileList){
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            String filename = UUID.randomUUID().toString()+"."+suffix;
            // 定义常见的图片格式的扩展名列表
            List<String> imageExtensions = Arrays.asList("jpg", "jpeg", "png", "gif");
            List<String> videoExtensions = Collections.singletonList("mp4");
            boolean isImage = imageExtensions.contains(suffix.toLowerCase());
            boolean isVideo = videoExtensions.contains(suffix.toLowerCase());
            Integer type;
            if (isImage){
                type = 0 ;
            }else if (isVideo){
                type = 1 ;
            }else {
                throw new RuntimeException("文件格式错误");
            }
            //file.transferTo(new File("F:\\files\\"+filename));
            String url = AliOssUtil.uploadFile(filename,file.getInputStream());
            File file1 = new File();
            file1.setFileName(filename);
            file1.setFileUrl(url);
            file1.setFileType(type);
            file1.setTime(new Date());
            fileService.save(file1);
            fileIdList.add(file1.getId());
        }
        return Result.success(fileIdList);
    }

    @Override
    public List<String> list(Integer trendsId) {
        return trendsFileDao.list(new QueryWrapper<TrendsFile>().eq("trends_id",trendsId));
    }
}
